package com.humanminoritygame.model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.Type;
import org.joda.time.DateTime;

@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"roundId", "subscriptionId"})})
public class UserRoundResult extends PersistentEntity implements Comparable<UserRoundResult> {

  @Enumerated(EnumType.STRING)
	private AnswerType answer;
	
	@ManyToOne
  @JoinColumn(name="subscriptionId")
	private Subscription subscription;
	
	private int points = 0;
	private int roundAcumulatedPoints =0;
	
	@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
	private DateTime time;
	
	@ManyToOne(cascade = CascadeType.ALL)
  @JoinColumn(name="roundId")
	private Round round;
	
	UserRoundResult() {
  }

	@Deprecated
	public UserRoundResult(AnswerType answer, Subscription subscription) {
	  super();
		this.answer = answer;
		this.subscription = subscription;
		time = new DateTime();
	}

	public UserRoundResult(AnswerType answer, Subscription subscription, Round round) {
		super();
		this.answer = answer;
		this.subscription = subscription;
		this.round = round;
		time = new DateTime();
	}

	public AnswerType getAnswer() {
		return answer;
	}

	public int getPoints() {
		return points;
	}

	public void setAnswer(AnswerType answer) {
		this.answer = answer;
	}

	public void setPoints(int points) {
		this.points = points;
	}
	
	public void addScore(int point){
	  //esto deberia cambiar cuando cambie el sistema de representar los puntos
	  int result = (int)Math.signum(point);
	  setPoints(result);
	  this.setRoundAcumulatedPoints(this.subscription.addScore(result));
	}
	
	@Override
	public boolean equals(Object obj) {
		// TODO Auto-generated method stub
		return super.equals(obj);
	}

	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return super.hashCode();
	}

	@Override
	public int compareTo(UserRoundResult o) {
		if (this.equals(o)) {
			return 0;
		}
		if (o.time.isAfter(time)) {
			return 1;
		} else if (o.time.isBefore(time)) {
			return -1;
		} else {
			if (equals(o)) {
				return 1;
			} else {
				return -1;
			}
		}
	}

	public DateTime getTime() {
		return time;
	}

	public Subscription getSubscription() {
		return subscription;
	}

	public Round getRound() {
		return round;
	}

  public void setRoundAcumulatedPoints(int roundAcumulatedPoints) {
    this.roundAcumulatedPoints = roundAcumulatedPoints;
  }


  public int getRoundAcumulatedPoints() {
    return roundAcumulatedPoints;
  }

}
